using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace Walkmen.ID3v1
{
    public class ID3v1Tag
    {
        private string _title;
        private string _artist;
        private string _album;
        private string _year;
        private string _comment;
        private byte _track;
        private byte _genre;

        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }

        public string Artist
        {
            get { return _artist; }
            set { _artist = value; }
        }

        public string Album
        {
            get { return _album; }
            set { _album = value; }
        }

        public string Year
        {
            get { return _year; }
            set { _year = value; }
        }

        public string Comment
        {
            get { return _comment; }
            set { _comment = value; }
        }

        public byte Track
        {
            get { return _track; }
            set { _track = value; }
        }

        public byte Genre
        {
            get { return _genre; }
            set { _genre = value; }
        }

        public byte[] ToArray()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                byte[] identifier = Encoding.ASCII.GetBytes("TAG");
                stream.Write(identifier, 0, identifier.Length);

                byte[] title = ToArray(_title, 30);
                stream.Write(title, 0, title.Length);

                byte[] artist = ToArray(_artist, 30);
                stream.Write(artist, 0, artist.Length);

                byte[] album = ToArray(_album, 30);
                stream.Write(album, 0, album.Length);

                byte[] year = ToArray(_year, 4);
                stream.Write(year, 0, year.Length);

                byte[] comment = ToArray(_comment, 28);
                stream.Write(comment, 0, comment.Length);

                stream.WriteByte(0x00);
                stream.WriteByte(_track);
                stream.WriteByte(_genre);

                return stream.ToArray();

            }
        }

        private byte[] ToArray(string text, int length)
        {
            byte[] result = new byte[length];
            if (text != null)
            {
                byte[] value = Encoding.Default.GetBytes(text);

                int size = value.Length;
                if (size >= length)
                {
                    size = length;
                }

                Array.Copy(value, result, size);
            }

            return result;
        }
    }
}
